package com.cskaoyan.market.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/6/20 9:34
 * @Version 1.0
 */
@WebListener
public class AppListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        loadAuth(sce);
    }


    //加载认证文件
    private void loadAuth(ServletContextEvent sce) {
        //auth.txt最终在运行的时候，是位于classpath目录中的，所以使用类加载器来获取位于该目录下的文件
        List<String> uris = new ArrayList<>();
        ClassLoader classLoader = AppListener.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("auth.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                uris.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将加载到的配置文件放入context域中
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute("uris", uris);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
